<template>
	<view class="user" :class="[isDark?'dark':'', $store.state.AppStyle]" :style="{'background-color':isDark?'#1c1c1c':'#f6f6f6','min-height':isDark?'100vh':'auto'}">
		<view class="header" :style="[{height:CustomBar + 'px'}]">
			<view class="cu-bar bg-white" :style="{'height': CustomBar + 'px','padding-top':StatusBar + 'px'}">
				<view class="action" @tap="back">
					<text class="cuIcon-back"></text>
				</view>
				<view class="content text-bold" :style="[{top:StatusBar + 'px'}]">
					<block v-if="type=='add'">
						{{$t('manage.sectionedit.addcircle')}}
					</block>
					<block v-else>
						{{$t('manage.sectionedit.editcircle')}}
					</block>
				</view>
				<!--  #ifdef H5 || APP-PLUS -->
				<view class="action" @tap="edit" v-if="type=='edit'">
					<button class="cu-btn round bg-blue">{{$t('global.save')}}</button>
				</view>
				<view class="action" @tap="add" v-if="type=='add'">
					<button class="cu-btn round bg-blue">{{$t('global.submit')}}</button>
				</view>
				<!--  #endif -->
			</view>
		</view>
		<view :style="[{padding:NavBar + 'px 10px 0px 10px'}]"></view>
		
		<form>
			<view class="user-edit-header margin-top">
				<image :src="pic"></image>
				<text class="cu-btn bg-blue radius" @tap="toAvatar" >{{$t('manage.sectionedit.setcircleicon')}}</text>
			</view>
			<view class="cu-form-group margin-top"  v-if="type=='edit'">
				<view class="title">{{$t('global.id')}}</view>
				<input name="input" disabled :value="id"/>
			</view>
			<view class="cu-form-group margin-top">
				<view class="title">{{$t('manage.sectionedit.category')}}</view>
				<input name="input" type="text" v-for="item in sectionList" v-if="item.id == parent" :value="item.name" disabled="disabled"/>
				<view class="action" v-if="type=='edit'">
					<text class="text-blue" @tap="showModal" data-target="sectionList">{{$t('global.move')}}</text>
				</view>
			</view>
			<view class="cu-form-group">
				<view class="title">{{$t('global.name')}}</view>
				<input name="input" type="text" v-model="name"/>
			</view>
			<view class="cu-form-group">
				<view class="title">{{$t('global.shortname')}}</view>
				<input name="input" type="text" v-model="slug" placeholder="$t('manage.sectionedit.urlencode')"/>
			</view>
			<view class="cu-form-group align-start">
				<view class="title">{{$t('global.remark')}}</view>
				<textarea v-model="text" placeholder="$t('global.plsremark')"></textarea>
			</view>
			<view class="cu-form-group margin-top">
				<view class="title">{{$t('global.sort')}}</view>
				<input name="input" type="number" v-model="order" placeholder="$t('global.sorthigher')"/>
			</view>
			<view class="cu-form-group">
				<view class="title">{{$t('manage.sectionedit.postpermiss')}}</view>
				<view class="picker" @tap="showModal" data-target="restrictList">
					{{restrictList[restrict].name}}
					<text class="cuIcon-right"></text>
				</view>
			</view>
			<view class="cu-form-group">
				<view class="title">{{$t('manage.sectionedit.backdrop')}}</view>
				<view class="action">
					<text class="cu-btn bg-blue radius" @tap="imgUpload">{{$t('global.uploadpic')}}</text>
				</view>
			</view>
			<view class="pay-codeImg" v-if="bg!=''">
				<image :src="bg"></image>
			</view>
		</form>
		<!--  #ifdef MP -->
		<view class="post-update bg-blue" @tap="edit" v-if="type=='edit'">
			<text class="cuIcon-upload"></text>
		</view>
		<view class="post-update bg-blue" @tap="add" v-if="type=='add'">
			<text class="cuIcon-upload"></text>
		</view>
		<!--  #endif -->
		<view class="cu-modal" :class="modalName=='restrictList'?'show':''" @tap="hideModal">
			<view class="cu-dialog" @tap.stop="">
				<radio-group class="block" @change="RadioChange">
					<view class="cu-list menu text-left">
						<view class="cu-item" v-for="(item,index) in restrictList" :key="index">
							<label class="flex justify-between align-center flex-sub" @tap="setRestrict(item.id)">
								<view class="flex-sub">{{item.name}}</view>
								<radio class="round" :class="restrict==item.id?'checked':''" :checked="restrict==item.id?true:false"></radio>
							</label>
						</view>
					</view>
				</radio-group>
			</view>
		</view>
		<view class="cu-modal" :class="modalName=='sectionList'?'show':''" @tap="hideModal">
			<view class="cu-dialog" @tap.stop="">
				<radio-group class="block" @change="SectionRadioChange">
					<view class="cu-list menu text-left">
						<view class="cu-item" v-for="(item,index) in sectionList" :key="index">
							<label class="flex justify-between align-center flex-sub" @tap="setSection(item.id)">
								<view class="flex-sub">{{item.name}}</view>
								<radio class="round" :class="curSection==item.id?'checked':''" :checked="curSection==item.id?true:false"></radio>
							</label>
						</view>
					</view>
				</radio-group>
			</view>
		</view>
	</view>
</template>

<script>
	import { localStorage } from '../../js_sdk/mp-storage/mp-storage/index.js'
	// #ifdef H5 || APP-PLUS
	import { pathToBase64, base64ToPath } from '../../js_sdk/mmmm-image-tools/index.js'
	// #endif
	import darkModeMixin from '@/utils/darkModeMixin.js'
	export default {
		mixins: [darkModeMixin],
		data() {
			return {
				StatusBar: this.StatusBar,
				CustomBar: this.CustomBar,
				NavBar:this.StatusBar +  this.CustomBar,
				AppStyle:this.$store.state.AppStyle,
				token:"",
				sort: $t('global.selbigcategory'),
				parent:0,
				id:0,
				isHuaWei: this.$API.isHuaWei(),
				isTy: false,
				name:'',
				order:1,
				pic:'',
				picNew:"",
				bg:'',
				slug:'',
				text:'',
				restrict:0,
				
				type:"add",
				
				restrictList:[
					{
						'id':0,
						'name': $t('manage.sectionedit.ordinaryuser')
					},
					{
						'id':1,
						'name': $t('global.auditor')
					},
					{
						'id':2,
						'name': $t('global.marshal')
					},
					{
						'id':3,
						'name':$t('global.scircleleader')
					},
					{
						'id':4,
						'name':$t('global.circleleader')
					},
					{
						'id':5,
						'name':$t('global.circleleaderadmin')
					}
				],
				modalName: null,
				sectionList:[],
				curSection:0,
			}
		},
		onPullDownRefresh(){
			
		},
		onShow(){
			var that = this;
			if(localStorage.getItem('toAvatar')){
				var toAvatar = JSON.parse(localStorage.getItem('toAvatar'));
				that.avatarUpload(toAvatar.dataUrl);
			}else{
				
			}
			// #ifdef APP-PLUS
			//plus.navigator.setStatusBarStyle("dark")
			// #endif
		},
		onLoad(res) {
			var that = this;
			// #ifdef APP-PLUS || MP
			that.NavBar = that.CustomBar;
			// #endif
			if(localStorage.getItem('token')){
				that.token = localStorage.getItem('token');
			}
			if(res.type){
				that.type = res.type;
			}
			if(res.sort){
				that.sort = res.sort;
			}
			if(res.parent){
				that.parent = res.parent;
				that.curSection  = res.parent;
			}
			if(res.name){
				that.sort = res.name;
			}
			if(res.id){
				that.id = res.id;
				that.getSectionInfo();
			}
			that.getSectionList();
		},
		methods: {
			back(){
				uni.navigateBack({
					delta: 1
				});
			},
			showModal(e) {
				this.modalName = e.currentTarget.dataset.target
			},
			hideModal(e) {
				this.modalName = null
			},
			RadioChange(e) {
				this.radio = e.detail.value
			},
			SectionRadioChange(e){
				this.curSection = e.detail.value;
			},
			setRestrict(id){
				let that = this	
				that.restrict = id;
				that.hideModal();
			},
			setSection(id){
				let that = this	
				that.curSection = id;
				var list = that.sectionList;
				for(var i in list){
					if(list[i].id==that.curSection){
						that.sort = list[i].name;
					}
				}
				that.hideModal();
			},
			// #ifdef APP-PLUS
			//权限检测
			showTC(){
				var that = this;
				var tc1 = false;
				let _permissionID = 'android.permission.WRITE_EXTERNAL_STORAGE';
				let _permissionID2 = 'android.permission.CAMERA';
				plus.android.checkPermission(_permissionID2,
					granted => {
						if (granted.checkResult == -1) {
							uni.showModal({
								title: that.$t('global.permissionapply'),
								content: that.$t('global.permissionapplydesc'),
								cancelText: that.$t('common.cancel'),
								confirmText: that.$t('global.agree'),
								showCancel: true,
								confirmColor: '#000',
								cancelColor: '#666',
								success: (res) => {
									if (res.confirm) {
										tc1 = true;
										that.requestPermissions();
									}else{
										that.isTy = false
										tc1 = true;
									}
								}
							})
							//还未授权当前查询的权限，打开权限申请目的自定义弹框
							that.$nextTick(() => {
								setTimeout(() => {
									that.ani = 'uni-' + that.type
								},30)
							})
						}
					},
					error => {
						console.log(error.message);
					}
				);
				plus.android.checkPermission(_permissionID,
					granted => {
						if (granted.checkResult == -1) {
							if(!tc1){
								uni.showModal({
									title: that.$t('global.permissionapply'),
									content: that.$t('global.permissionapplydesc'),
									cancelText: that.$t('common.cancel'),
									confirmText: that.$t('global.agree'),
									showCancel: true,
									confirmColor: '#000',
									cancelColor: '#666',
									success: (res) => {
										if (res.confirm) {
											return that.requestPermissions();
										}else{
											that.isTy = false
										}
									}
								})
							}
							//还未授权当前查询的权限，打开权限申请目的自定义弹框
							that.$nextTick(() => {
								setTimeout(() => {
									that.ani = 'uni-' + that.type
								},30)
							})
						}
					},
					error => {
						console.log(error.message);
					}
				);
				
			},
			requestPermissions() {
				let _this = this;
				let _permissionID = 'android.permission.WRITE_EXTERNAL_STORAGE';
				let _permissionID2 = 'android.permission.CAMERA';
				
				plus.android.checkPermission(_permissionID2,
					granted => {
						if (granted.checkResult == -1) {
							//还未授权当前查询的权限，打开权限申请目的自定义弹框
							_this.$nextTick(() => {
								setTimeout(() => {
									_this.ani = 'uni-' + _this.type
								},30)
							})
						}
					},
					error => {
						console.log(error.message);
					}
				);
				plus.android.requestPermissions([_permissionID2],
					(e) => {
					//关闭权限申请目的自定义弹框
					_this.ani = '';
					_this.$nextTick(() => {
						
					})
					if (e.granted.length > 0) {
						//当前查询权限已授权
						plus.android.checkPermission(_permissionID,
							granted => {
								if (granted.checkResult == -1) {
									//还未授权当前查询的权限，打开权限申请目的自定义弹框
									_this.$nextTick(() => {
										setTimeout(() => {
											_this.ani = 'uni-' + _this.type
										},30)
									})
								}
							},
							error => {
								console.log(error.message);
							}
						);
						plus.android.requestPermissions([_permissionID],
							(e) => {
								//关闭权限申请目的自定义弹框
								_this.ani = '';
								_this.$nextTick(() => {
									
								})
								if (e.granted.length > 0) {
									//当前查询权限已授权
									_this.isTy = true
								}
								if (e.deniedAlways.length > 0) {
									//当前查询权限已被永久禁用，此时需要引导用户跳转手机系统设置去开启
									uni.showModal({
										title: _this.$t('global.fogettips'),
										content: _this.$t('global.noalbumpermiss'),
										cancelText: _this.$t('common.cancel'),
										confirmText: _this.$t('global.setitup'),
										showCancel: true,
										confirmColor: '#000',
										cancelColor: '#666',
										success: (res) => {
											if (res.confirm) {
												_this.goSetting();
											}else{
												_this.isTy = false
											}
										}
									})
								}
							})
						}
						if (e.deniedAlways.length > 0) {
							//当前查询权限已被永久禁用，此时需要引导用户跳转手机系统设置去开启
							uni.showModal({
								title: _this.$t('global.fogettips'),
								content: _this.$t('global.nocamerapermiss'),
								cancelText: _this.$t('common.cancel'),
								confirmText: _this.$t('global.setitup'),
								showCancel: true,
								confirmColor: '#000',
								cancelColor: '#666',
								success: (res) => {
									if (res.confirm) {
										_this.goSetting();
									}else{
										_this.isTy = false
									}
								}
							})
						}
					})
			},
			//跳转手机系统设置
			goSetting() {
				var Intent = plus.android.importClass("android.content.Intent");
				var Settings = plus.android.importClass("android.provider.Settings");
				var Uri = plus.android.importClass("android.net.Uri");
				var mainActivity = plus.android.runtimeMainActivity();
				var intent = new Intent();
				intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
				intent.setData(uri);
				mainActivity.startActivity(intent);
			},
			// #endif
			imgUpload(){
				let that = this		
				if(that.isTy==false&&that.isHuaWei==1){
					that.showTC()
				}
				uni.chooseImage({
					count: 1,  // 最多可以选择的图片张数，默认9
					sourceType: ['album', 'camera'], 
				    success: function (res) {						
						uni.showLoading({
							title: that.$t('common.loadmore')
						});
						const tempFilePaths = res.tempFilePaths;
						const uploadTask = uni.uploadFile({
						  url : that.$API.upload(),
						  filePath: tempFilePaths[0],
						  name: 'file',
						  formData: {
						   'token': that.token
						  },
						  success: function (uploadFileRes) {
							  setTimeout(function () {
							  	uni.hideLoading();
							  }, 1000);
							var data = JSON.parse(uploadFileRes.data);
							uni.showToast({
								title: data.msg,
								icon: 'none'
							})
							if(data.code==1){
								that.bg = data.data.url;
							}
							},fail:function(){
								setTimeout(function () {
									uni.hideLoading();
								}, 1000);
							}
						});
					 
						uploadTask.onProgressUpdate(function (res) {
						  
						 });
					}
				})
			},
			avatarUpload(base64){
				var that = this;
				base64ToPath(base64)
					.then(path => {
						var file = path;
						const uploadTask = uni.uploadFile({
						url : that.$API.upload(),
						filePath:file,
					 //  header: {
						// "Content-Type": "multipart/form-data",
					 // },
						name: 'file',
						formData: {
							'token': that.token
						},
						success: function (uploadFileRes) {
							setTimeout(function () {
								uni.hideLoading();
							}, 1000);
							var data = JSON.parse(uploadFileRes.data);
							if(data.code==1){
								// uni.showToast({
								// 	title: data.msg,
								// 	icon: 'none'
								// })
								that.pic = data.data.url;
								that.picNew = data.data.url;
								localStorage.removeItem('toAvatar');
								// that.userEdit();
							}else{
								uni.showToast({
									title: that.$t('global.uploadpicfail'),
									icon: 'none'
								})
							}
						},fail:function(){
							setTimeout(function () {
								uni.hideLoading();
							}, 1000);
						}
					});
				})
				.catch(error => {
					console.error("失败"+error)
				})
			},
			add(){
				var that = this;
				if(that.parent==0){
					uni.showToast({
						title: that.$t('global.selbigcategory'),
						icon:'none',
						duration: 1000,
						position:'bottom',
					});
					return false
				}
				if (that.name == ""||that.order == "") {
					uni.showToast({
						title: that.$t('global.plsformfill'),
						icon:'none',
						duration: 1000,
						position:'bottom',
					});
					return false
				}
				var data = {
					'name':that.name,
					'order':that.order,
					'parent':that.parent,
					'bg':that.bg,
					'text':that.text,
					'pic':that.pic,
					'slug':that.slug,
					'type':"section",
					"token":that.token,
					"restrict":that.restrict
				}
				uni.showLoading({
					title: that.$t('common.loadmore')
				});
				that.$Net.request({
					url: that.$API.addSection(),
					data:that.$API.removeObjectEmptyKey(data),
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						setTimeout(function () {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
						if(res.data.code==1){
							var timer = setTimeout(function() {
								that.back();
							}, 1000)
						}
					},
					fail: function(res) {
						setTimeout(function () {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
						uni.stopPullDownRefresh()
					}
				})
			},
			getSectionInfo(){
				var that = this;
				that.$Net.request({
					url: that.$API.sectionInfo(),
					data:{
						"id":that.id
					},
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if(res.data.code==1){
							that.name = res.data.data.name;
							that.order = res.data.data.orderKey;
							that.pic = res.data.data.pic;
							that.picNew = res.data.data.pic;
							that.bg = res.data.data.bg;
							that.slug = res.data.data.slug;
							that.text = res.data.data.text;
							that.restrict = res.data.data.restrictKey;
						}
					},
					fail: function(res) {
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
					}
				})
			},
			edit(){
				var that = this;
				if(that.parent==0){
					uni.showToast({
						title: that.$t('global.selbigcategory'),
						icon:'none',
						duration: 1000,
						position:'bottom',
					});
					return false
				}
				if (that.name == ""||that.order == "") {
					uni.showToast({
						title: that.$t('global.plsformfill'),
						icon:'none',
						duration: 1000,
						position:'bottom',
					});
					return false
				}
				var data = {
					'id':that.id,
					'name':that.name,
					'order':that.order,
					'parent':that.curSection,
					'bg':that.bg,
					'text':that.text,
					'slug':that.slug,
					'pic':that.pic,
					'type':"section",
					"token":that.token,
					"restrict":that.restrict
				}
				uni.showLoading({
					title: that.$t('common.loadmore')
				});
				that.$Net.request({
					url: that.$API.editSection(),
					data:that.$API.removeObjectEmptyKey(data),
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						setTimeout(function () {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
						if(res.data.code==1){
							var timer = setTimeout(function() {
								that.back();
							}, 1000)
							
						}
					},
					fail: function(res) {
						setTimeout(function () {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
						uni.stopPullDownRefresh()
					}
				})
			},
			toAvatar(){
				// #ifdef APP-PLUS || H5
				const that = this;
				  uni.navigateTo({
					url: "../../uni_modules/buuug7-img-cropper/pages/cropper",
					events: {
					  imgCropped(event) {
						console.log(event);
					  },
					},
				  });
				// #endif
			},
			getSectionList(){
				var that = this;
				var data = {
					"parent":0,
				}
				that.$Net.request({
					url: that.$API.sectionList(),
					data:{
						"searchParams":JSON.stringify(that.$API.removeObjectEmptyKey(data)),
						"limit":50,
						"page":1,
					},
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if(res.data.code==1){
							var list = res.data.data;
							that.sectionList = list;
						}
						var timer = setTimeout(function() {
							that.isLoading=1;
							clearTimeout('timer')
						}, 300)
					},
					fail: function(res) {
						
					}
				})
			},
		}
	}
</script>